#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEngine.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Unity.Plastic.Newtonsoft.Json;
using System.IO;
namespace MeEditor
{
    public class EditorUtil
    {
        

        //添加菜单从服务器更新uxsystem.json文件接口
        // [MenuItem("MeEditor/预设管理/拉取最新")]
        public static async void UpdateUXSystemJson()
        {
            try
            {
                string url = Configure.ServerUrl + "get_uxsystem";
                using (UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get(url))
                {
                    // 添加项目UUID验证
                    www.SetRequestHeader("X-Project-UUID", Configure.ProjectUUID);
                    var operation = www.SendWebRequest();
                    // 异步显示进度
                    while (!operation.isDone)
                    {
                        EditorUtility.DisplayProgressBar("拉取最新", "正在连接服务器...", www.downloadProgress);
                        await Task.Delay(100);
                    }
                    EditorUtility.ClearProgressBar();
                    if (www.result != UnityEngine.Networking.UnityWebRequest.Result.Success)
                    {
                        Debug.LogError($"同步失败：{www.error}");
                        EditorUtility.DisplayDialog("同步失败", $"服务器连接错误：{www.error}", "确定");
                        return;
                    }
                    // 验证JSON格式
                    string json = www.downloadHandler.text;
                    if (!IsValidJson(json))
                    {
                        throw new Exception("无效的JSON格式");
                    }
                    // 保存到本地
                    string localPath = Configure.ResAssetsPath + "/UXSystem.json";
                    File.WriteAllText(localPath, json);
                    // 刷新编辑器
                    AssetDatabase.Refresh();
                    EditorUtility.DisplayDialog("同步成功", "UX配置文件已更新", "确定");
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"同步异常：{e.Message}");
                EditorUtility.DisplayDialog("同步失败", $"发生异常：{e.Message}", "确定");
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }
        //添加接口 本地json上传到服务器
        // [MenuItem("MeEditor/预设管理/上传本地")]
        public static async void UploadUXSystemJson()
        {
            try
            {
                string localPath = Configure.ResAssetsPath + "/UXSystem.json";
                if (!File.Exists(localPath))
                {
                    EditorUtility.DisplayDialog("上传失败", "本地配置文件不存在", "确定");
                    return;
                }

                string jsonContent = File.ReadAllText(localPath);
                if (!IsValidJson(jsonContent))
                {
                    EditorUtility.DisplayDialog("上传失败", "本地JSON格式无效", "确定");
                    return;
                }

                string url = Configure.ServerUrl + "update_uxsystem";
                using (UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.PostWwwForm(url, "POST"))
                {
                    // 添加项目UUID验证
                    www.SetRequestHeader("X-Project-UUID", Configure.ProjectUUID);
                    byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonContent);
                    www.uploadHandler = new UnityEngine.Networking.UploadHandlerRaw(bodyRaw);
                    www.downloadHandler = new UnityEngine.Networking.DownloadHandlerBuffer();
                    www.SetRequestHeader("Content-Type", "application/json");

                    var operation = www.SendWebRequest();
                    
                    while (!operation.isDone)
                    {
                        EditorUtility.DisplayProgressBar("上传中", "正在上传配置文件...", www.uploadProgress);
                        await Task.Delay(100);
                    }

                    EditorUtility.ClearProgressBar();

                    if (www.result != UnityEngine.Networking.UnityWebRequest.Result.Success)
                    {
                        Debug.LogError($"上传失败：{www.error}");
                        EditorUtility.DisplayDialog("上传失败", $"服务器错误：{www.error}", "确定");
                        return;
                    }

                    EditorUtility.DisplayDialog("上传成功", "配置文件已同步到服务器", "确定");
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"上传异常：{e.Message}");
                EditorUtility.DisplayDialog("上传失败", $"发生异常：{e.Message}", "确定");
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }

        private static bool IsValidJson(string str)
        {
            try
            {
                JsonConvert.DeserializeObject<SystemFather[]>(str);
                return true;
            }
            catch
            {
                return false;
            }
        }


    }
}
#endif